﻿using FireChat.Share.Logger.Printer;
using System.Collections;

namespace FireChat.Share.Logger;


/// <summary>
/// 日志缓存
/// </summary>
public class LogBuffer : IEnumerable<ILogPrinter>
{
    /// <summary>
    /// 日志缓冲区
    /// </summary>
    private readonly Queue<ILogPrinter> _logs = new();

    /// <summary>
    /// 缓冲区大小
    /// </summary>
    public uint MaxSize { get; }

    /// <summary>
    /// 当前日志数量
    /// </summary>
    public int Count => _logs.Count;



    /// <summary>
    /// 初始化日志缓存
    /// </summary>
    /// <param name="maxSize">缓冲区大小</param>
    public LogBuffer(uint maxSize) => MaxSize = maxSize;



    /// <summary>
    /// 添加一个日志
    /// </summary>
    public void Push(ILogPrinter log)
    {
        _logs.Enqueue(log);

        if (_logs.Count >= MaxSize)
        {
            _logs.TryDequeue(out var _);
        }
    }

    /// <summary>
    /// 查看第一个日志
    /// </summary>
    /// <returns></returns>
    public ILogPrinter Peep()
    {
        return _logs.Peek();
    }

    /// <summary>
    /// 弹出第一个日志
    /// </summary>
    public ILogPrinter? Pop()
    {
        _logs.TryDequeue(out var log);
        return log;
    }



    /// <summary>
    /// 获取迭代器
    /// </summary>
    public IEnumerator<ILogPrinter> GetEnumerator()
    {
        return _logs.GetEnumerator();
    }

    /// <summary>
    /// 获取迭代器
    /// </summary>
    IEnumerator IEnumerable.GetEnumerator()
    {
        return _logs.GetEnumerator();
    }
}
